package com.jianguozh.difs.support.api.ops;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jianguozh.difs.common.bean.R;
import com.jianguozh.difs.framework.base.BaseController;
import com.jianguozh.difs.framework.constant.SecurityConstant;
import com.jianguozh.difs.framework.validator.group.AddGroup;
import com.jianguozh.difs.framework.validator.group.UpdateGroup;
import com.jianguozh.difs.support.api.ops.dto.ResBodyDto;
import com.jianguozh.difs.support.api.ops.dto.ResDto;
import com.jianguozh.difs.support.api.ops.dto.ResHeaderDto;
import com.jianguozh.difs.support.service.sys.entity.Res;
import com.jianguozh.difs.support.service.sys.service.IResService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 资源 前端控制器
 * </p>
 *
 * @author hanrs
 * @since 2022-03-17
 */
@RestController
@RequestMapping("/res")
public class ResController extends BaseController {

    @Autowired
    IResService resService;

    /**
     * 由id获取对象
     */
    @GetMapping("/{id}")
    public R<Res> get(@PathVariable String id) {
        return success(resService.getById(id));
    }

    /**
     * 新增头部
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_OPS + "')")
    @PostMapping("/header")
    public R<Res> addHeader(@RequestBody @Validated(value = {AddGroup.class}) ResHeaderDto resHeaderDto) {
        Res entity = new Res();
        BeanUtil.copyProperties(resHeaderDto, entity);
        boolean result = resService.saveOrUpdate(entity);
        return result ? success(entity) : failed("操作失败.");
    }

    /**
     * 修改头部
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_OPS + "')")
    @PutMapping("/header")
    public R<Res> modifyHeader(@RequestBody @Validated(value = {UpdateGroup.class}) ResHeaderDto resHeaderDto) {
        Res entity = new Res();
        BeanUtil.copyProperties(resHeaderDto, entity);
        boolean result = resService.saveOrUpdate(entity);
        return result ? success(entity) : failed("操作失败.");
    }

    /**
     * 修改身体
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_OPS + "')")
    @PutMapping("/body")
    public R<Res> modifyBody(@RequestBody @Validated(value = {UpdateGroup.class}) ResBodyDto resBodyDto) {
        Res entity = new Res();
        BeanUtil.copyProperties(resBodyDto, entity);
        boolean result = resService.saveOrUpdate(entity);
        return result ? success(entity) : failed("操作失败.");
    }

    /**
     * 新增
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_OPS + "')")
    @PostMapping("")
    public R<Res> add(@RequestBody @Validated(value = {AddGroup.class}) ResDto resDto) {
        long count = resService.count(new LambdaQueryWrapper<Res>().eq(Res::getResName, resDto.getResName()));
        if (count > 0) {
            return failed("已经存在'" + resDto.getResName() + "'的资源.");
        }

        Res entity = new Res();
        BeanUtil.copyProperties(resDto, entity);
        boolean result = resService.saveOrUpdate(entity);
        return result ? success(entity) : failed("操作失败.");
    }

    /**
     * 修改
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_OPS + "')")
    @PutMapping("")
    public R<Res> modify(@RequestBody @Validated(value = {UpdateGroup.class}) ResDto resDto) {
        long count = resService.count(new LambdaQueryWrapper<Res>().eq(Res::getResName, resDto.getResName()).ne(Res::getId, resDto.getId()));
        if (count > 0) {
            return failed("已经存在'" + resDto.getResName() + "'的资源.");
        }

        Res entity = new Res();
        BeanUtil.copyProperties(resDto, entity);
        boolean result = resService.saveOrUpdate(entity);
        return result ? success(entity) : failed("操作失败.");
    }

    /**
     * 单个删除
     */
    @PreAuthorize("hasAnyAuthority('" + SecurityConstant.AUTHORITY_TAG_OPS + "')")
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable String id) {
        boolean result = resService.removeById(id);
        return result ? success(true) : failed("操作失败.");
    }

    /**
     * 条件查询
     *
     * @param clientId
     * @return
     */
    @GetMapping("/list/{clientId}")
    public R<List<Tree<String>>> list(@PathVariable String clientId) {
        List<Res> resList = resService.list(new LambdaQueryWrapper<Res>().eq(Res::getClientId, clientId));
        TreeNodeConfig config = new TreeNodeConfig();
        config.setWeightKey("sort").setParentIdKey("parentId").setIdKey("id").setChildrenKey("children");
        List<Tree<String>> trees = TreeUtil.build(resList, null, config, (obj, tree) -> {
            tree.setParentId(obj.getParentId());
            tree.setId(obj.getId());
            tree.putExtra("sort", obj.getSort());
            tree.putExtra("key", obj.getId());
            tree.putExtra("parentKey", obj.getParentId());
            tree.putExtra("clientId", obj.getClientId());
            tree.putExtra("title", obj.getResName());
            tree.putExtra("badge", obj.getBadge());
            tree.putExtra("icon", obj.getIcon());
            tree.putExtra("path", obj.getPath());
            tree.putExtra("component", obj.getComponent());
            tree.putExtra("permission", obj.getPermission());
        });
        return success(trees);
    }


}
